/****************************************************************************
 * 	 <SPG2 - Secure Password Generator>
 *   Copyright (C) 2010  <Robert Carr>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *   
 *   @author Robert Carr (etftw)
 *   @version 2.4
 *   
 ***************************************************************************/

package spg2;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import javax.swing.*;

public class PasswordDialog extends JDialog implements ActionListener 
{
	private static final long serialVersionUID = -4365850705012233689L;
	private JLabel jlbPassword;
	
	/**
	 * Copies the password to the system clipboard
	 */
	private void copyToClipboard()
	{
		Clipboard cp = Toolkit.getDefaultToolkit().getSystemClipboard(); 
		Transferable script = new StringSelection( this.jlbPassword.getText() );
		try
		{
			cp.setContents( script, null ); 
			JOptionPane.showMessageDialog(this, "The password was copied to the clipboard!"
					, "SPG2", JOptionPane.INFORMATION_MESSAGE );
		}
		catch ( IllegalStateException e )
		{
			JOptionPane.showMessageDialog(this, "The password could not be copied to the clipboard!\n"
					+ "If the problem persists please report the error via http://code.google.com/p/spg2/"
					+ "\n\nError details: " + e.getMessage()
					, "Error", JOptionPane.ERROR_MESSAGE );
		}
	}
	
	/**
	 * Saves the password to a file specified by the user
	 */
	private void saveToFile()
	{
		FileDialog fd = new FileDialog( this, "Select a file..." );
		fd.setMode( FileDialog.SAVE );
		fd.setVisible( true );
		
		if( fd.getFile() != null )
		{
			try
			{
				File sf = new File( fd.getDirectory() + fd.getFile() );
				Writer output = new BufferedWriter( new FileWriter( sf ) );
				
				if( ! sf.canWrite() )
				{
					throw new IOException("File cannot be written to.");
				}
				
				output.write( this.jlbPassword.getText() );
				output.close();
				JOptionPane.showMessageDialog( null, "Password was saved to " +
						fd.getDirectory() + fd.getFile(), "Saved", JOptionPane.INFORMATION_MESSAGE );
			}
			catch ( IOException e )
			{
				JOptionPane.showMessageDialog(this, "The password could not be saved!\n"
						+ "If the problem persists please report the error via http://code.google.com/p/spg2/"
						+ "\n\nError details: " + e.getMessage()
						, "Error", JOptionPane.ERROR_MESSAGE );
			}
		}
	}
	
	/**
	 * Initialises and sets up the dialog window that the generated password will be displayed in
	 * @param parent the parent JFrame (i.e. the main SPG2 window)
	 * @param title the caption of the dialog
	 * @param password the password that should be displayed
	 */
	public PasswordDialog(JFrame parent, String title, String password) 
	{
		super(parent, title, true);
	    if (parent != null) 
	    {
	      Dimension parentSize = parent.getSize(); 
	      Point p = parent.getLocation(); 
	      setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
	    } 
	    
	    this.jlbPassword = new JLabel(password);
	    Font f = this.jlbPassword.getFont();
	    this.jlbPassword.setFont(f.deriveFont(Font.BOLD, 15));
	    this.jlbPassword.setVisible( true );
	    
	    JButton jbtCopy = new JButton( "Copy to clipboard" );
	    jbtCopy.addActionListener( new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				copyToClipboard();
			}
	    });
	    jbtCopy.setVisible( true );
	    
	    JButton jbtSave = new JButton( "Save" );
	    jbtSave.addActionListener( new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				saveToFile();
			}
	    });
	    jbtSave.setVisible( true );
	    
	    JPanel jpaButtons = new JPanel();
	    jpaButtons.setLayout( new FlowLayout() );
	    jpaButtons.add( jbtCopy );
	    jpaButtons.add( Box.createHorizontalStrut( 5 ) );
	    jpaButtons.add( jbtSave );
	    jpaButtons.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
	    
	    JPanel jpaPassword = new JPanel();
	    jpaPassword.setLayout( new FlowLayout() );
	    jpaPassword.add(this.jlbPassword);
	    
	    getContentPane().add( jpaPassword, BorderLayout.CENTER );
	    getContentPane().add( jpaButtons, BorderLayout.PAGE_END );
	    
	    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
	    this.setSize( 282, 149 );
	    pack();
	    setVisible(true);
	  }
	
	public void actionPerformed(ActionEvent e) 
	  {
	    setVisible(false); 
	    dispose(); 
	  }
}
